package cn.touna.jss.modules.custom.batch;

import com.alibaba.fastjson.JSONObject;
import org.springframework.util.StringUtils;

import java.io.*;
public class CsvReader {

    private File src;
    private CsvReaderConfig config;

    public CsvReader(File src,CsvReaderConfig config){
        this.src = src;
        this.config = config;
    }

    private BufferedReader currBr = null;
    private boolean isClosed = false;
    private BufferedReader getBufferedReader() throws IOException {
        if(!isClosed && currBr == null && src.isFile()){
            currBr =  new BufferedReader(new FileReader(src));
            if(config.getSkipLine() > 0){
                int i = config.getSkipLine();
                while(i-->0){
                    String line = currBr.readLine();
                    if(line == null){
                        isClosed = true;
                        currBr.close();
                        currBr = null;
                        return null;
                    }

                }
            }
        }
        return currBr;
    }

    public synchronized JSONObject read() throws IOException {
        BufferedReader br = getBufferedReader();
        if(isClosed || br == null)
            return null;

        String line = br.readLine();
        if(line == null){
            br.close();
            isClosed = true;
            return null;
        }
        if(StringUtils.isEmpty(line)){
            return read();
        }

        String[] row = line.split(config.getSeperator());
        int columnLength = config.getColumns().length;
        JSONObject obj = new JSONObject();
        for(int i =0;i<columnLength;i++){
            String name = config.getColumns()[i];
            if(i<row.length){
                String value = row[i];
                if(!StringUtils.isEmpty(value))
                    value = value.trim();
                obj.put(name,value);
            }else{
                obj.put(name,null);
            }
        }
        return obj;
    }





}
